package com.example.eeuse.controller;


import com.example.eeuse.mapper.DocumentMapper;
import com.example.eeuse.model.Document;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.RequiredArgsConstructor;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

/**
 * 测试使用Easy-ES
 * <p>
 * Copyright © 2021 xpc1024 All Rights Reserved
 **/
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TestUseEeController {
    private final DocumentMapper documentMapper;
    private final MinioClient minioClient;

    @GetMapping("/createIndex")
    public Boolean createIndex() {
        System.out.println("初始化-> 创建索引");
        // 初始化-> 创建索引
        return documentMapper.createIndex();
    }

    @PostMapping("/insert")
    public String insert(@RequestParam("files") MultipartFile[] files, HttpServletResponse response) {
        try {
            if (files == null || files.length == 0) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return "文件为空，请选择一个文件进行上传。";
            }
            for (MultipartFile file : files){
                try(InputStream is = file.getInputStream()) {
                    minioClient.putObject(PutObjectArgs.builder()
                            .bucket("search")
                            .object(file.getOriginalFilename())
                            .stream(is, file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
                }
            }
            Document document = new Document();
            document.setId("542352352");
            document.setTitle("老汉");
            document.setContent("推*技术过硬");
            documentMapper.insert(document);
            System.err.println("OK");
            return "文件上传成功";
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return "文件上传失败: " + e.getMessage();
        }
    }

    @GetMapping("/search")
    public List<Document> search() {
        // 查询出所有标题为老汉的文档列表
        LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.eq(Document::getTitle, "老汉")
                .and(i -> i.eq(Document::getId, 1).eq(Document::getContent, "推车"))
                .or()
                .and(i -> i.eq(Document::getId, 2).eq(Document::getContent, "推土"));
        String source = documentMapper.getSource(wrapper);
        System.out.println(source);
        return documentMapper.selectList(wrapper);
    }
}
